package com.sxds.wn.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sxds.wn.IConstants;
import com.sxds.wn.security.dto.User;

/**
 * Description: <p>用户登陆过滤器</p>
 * Content Desc:<p>认证过滤器,所有请求必须进过此认证，未认证的请求系统自动转发至登录用户<p>
 * Copy Right of Personal Tangtao 2007-2020
 * @author Andy
 * @version 1.0 Create Date:@2008-11-10
 */
public class AuthenticationFilter extends HttpServlet implements Filter,IConstants {

	/**
	 * 默认登陆页面地址,Spring MVC path
	 */
	private static final String DEFAULT_LOGIN_PAGE = "login.spring";
	private static final String DEFAULT_ERROR_PAGE = "errors/error.html";
	
	private FilterConfig filterConfig;
	private String loginPage;
	private String errorsPage;
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		loginPage = filterConfig.getInitParameter("loginPage");
		if( loginPage==null ){
			this.loginPage = DEFAULT_LOGIN_PAGE;
		}
		this.errorsPage = DEFAULT_ERROR_PAGE;
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		this.loginPage = null;
		this.filterConfig = null;
		this.errorsPage=null;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		if( this.loginPage!=null && httpRequest.getServletPath().indexOf(this.loginPage)>0 ){
			//登陆页面，通过过滤器
			filterChain.doFilter(request, response);
		}else{
			HttpSession session = httpRequest.getSession(false);
			boolean isAuthented = false;
			if( session!=null ){
				User user = (User)session.getAttribute(USER_SESSION_KEY);
				if( user!=null ) isAuthented = true;
			}
			if( !isAuthented ){
				String contextPath = httpRequest.getContextPath();
				//用户登录有误
				/*if(httpRequest.getSession().getAttribute(PAGE_ERRORS_MESSAGES_KEY)!=null){
					httpResponse.sendRedirect(contextPath + "/"+this.errorsPage);
				}else{*/
				//未认证用户
				//RequestDispatcher dispatchr = request.getRequestDispatcher(loginPage);
				//dispatchr.forward(request, response);
				if(httpRequest.getHeader("x-requested-with")!=null        
						  && httpRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){       
					String encode = httpRequest.getCharacterEncoding();
					httpResponse.resetBuffer();
					httpResponse.setHeader("sessionstatus","timeout");
					String jsonText = "{'success':false,'msg':'用户超时，无法完成操作，系统将跳转至登录页面！','loginUrl':'" 
									  + contextPath + "/" + this.loginPage + "'}";
					httpResponse.setCharacterEncoding(encode);
					httpResponse.getWriter().write(jsonText);
					httpResponse.flushBuffer();
				}else{
					httpResponse.sendRedirect(contextPath + "/" + this.loginPage);
				}
			}else{
				//已认证用户,通过过滤器
				filterChain.doFilter(request, response);
			}
		}
	}
		
}
